<template>
  <div class="update-gender">
    <van-picker
      :default-index="defaultIndex"
      show-toolbar
      :columns="columns"
      @confirm="onConfirm"
      @cancel="$emit('close')"
      @change="onGenderChange"
    />
  </div>
</template>

<script>
import { updateUserProfile } from "@/api/user";

export default {
  name: "UpdateGender",
  props: ["value"],
  data() {
    return {
      columns: ["男", "女"],
      defaultIndex: this.value,
    };
  },
  methods: {
    // 改变性别
    onGenderChange(picker, value, index) {
      this.defaultIndex = index;
    },
    // 点击确认
    async onConfirm() {
      if (this.defaultIndex === this.value) return this.$emit("close");

      this.$toast.loading({
        message: "保存中...",
        forbidClick: true,
      });
      await updateUserProfile({
        gender: this.defaultIndex,
      });
      this.$emit("input", this.defaultIndex);
      this.$emit("close");
      this.$toast.success("保存成功");
    },
  },
};
</script>

<style></style>
